/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2013 www.pretty-tools.com
 */


/**
 * Profile factory/loader
 */
var wsshWebProfileSerializer = {
    logger: yrprxFactory.createLogger("wsshWebProfileSerializer")
};

wsshWebProfileSerializer.handlerPageChild = function(childNode, page)
{
    page.elementTag = childNode.getNodeName().toUpperCase();
    page.elementUrlAttribute = childNode.getAttribute("url_attribute");

    var elementPattern = childNode.getAttribute("pattern");
    page.elementPattern = elementPattern ? new RegExp(elementPattern, "i") : null;
    page.elementPatternAsString = elementPattern;

    if (!(page.elementTemplate = childNode.getAttribute("template")) && childNode.hasChildNodes())
    {
        page.elementTemplate = yrprxUtil.trim(childNode.getFirstNodeText("template"));
    }
}

wsshWebProfileSerializer.handlerPage = function(websitePage, item)
{
    var page = new wsshWebPageProfile();

    var pagePattern = websitePage.getAttribute("pattern");

    page.patternAsString = pagePattern ? pagePattern : ".*";
    page.pattern = new RegExp(page.patternAsString, "i");

    if (page.browser = websitePage.getAttribute("browser"))
        page.supported = (page.browser == "firefox") || (page.browser == "chrome");

    page.disabled = (websitePage.getAttribute("disabled") == "true");

    websitePage.enumerateChildElements(wsshWebProfileSerializer.handlerPageChild, page);

    item.pages.push(page);
}

wsshWebProfileSerializer.handlerWebsite = function(website, items)
{
    var item = new wsshWebDomainProfile(website.getAttribute("domain"));

    if (website.getAttribute("hidden") == "true")
        item.hidden = true;

    website.loadAttributes(item, ["signature", "checksum"]);

    website.enumerateElementsByTagName("page", wsshWebProfileSerializer.handlerPage, item);

    items.push(item);
}

wsshWebProfileSerializer.load = function(profile)
{
    this.logger.debug("load");
    try
    {
        if (!this.profileExists(profile))
            return new Array();

        var xml = new yrprxSimpleXMLParser(profile);

        var collection = xml.getElementsByTagName("profile");
        if (!collection || collection.length != 1)
            return new Array();

        var items = new Array();

        xml.enumerateElementsByTagName("website", wsshWebProfileSerializer.handlerWebsite, items);

        if (this.logger.enabled) this.logger.debug("load: loaded items: " + items.length);

        this.validate(items);

        return items;
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("load:", ex);
    }
    return new Array();
}

wsshWebProfileSerializer.validate = function(items)
{
    try
    {
        if (!yrprxFactory.trustHelperExists())
            return;

        yrprxFactory.getTrustHelper().validateRules(items.length, items);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("validate:", ex);
    }
}

wsshWebProfileSerializer.createXMLDocument = function(items)
{
    try
    {
        var builder = new yrprxSimpleXMLBuilder("profile");

        var savedCount = 0;
        for (var i = 0; i < items.length; ++i)
        {
            if (!items[i])
                continue;

            var websiteElement = builder.addNode("website");
            websiteElement.saveAttributes(items[i], ["domain", "signature", "checksum", "hidden"]);

            // save pages settings
            var pages = items[i].pages;
            for (var p in pages)
            {
                var page = pages[p];
                if (!page)
                    continue;

                var pageElement = websiteElement.addNode("page");
                // set pattern
                pageElement.addAttribute("pattern", page.pattern.source);
                pageElement.saveAttributes(page, ["browser", "disabled"]);

                var element = pageElement.addNode(page.elementTag);
                // set attributes
                element.addAttribute("pattern", page.elementPattern.source);
                element.addAttribute("url_attribute", page.elementUrlAttribute);
                if (!page.isJavaScriptTemplate())
                    element.addAttribute("template", page.elementTemplate);
                else
                    element.addNode("template", page.elementTemplate);

                ++savedCount;
            }
        }

        return (savedCount > 0) ? builder : null;
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("createXMLDocument:", ex);
    }
    return null;
}

wsshWebProfileSerializer.save = function(items, profile)
{
    this.logger.debug("save");
    try
    {
        var builder = this.createXMLDocument(items);

        if (builder != null)
            builder.save(profile);
        else
            this.removeProfile(profile);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("save:", ex);
    }
}

wsshWebProfileSerializer.getUserProfile = function()
{
    return this.getProfile("UserProfile");
}

wsshWebProfileSerializer.getPredefinedProfile = function()
{
    return this.getProfile("PredefinedProfile");
}

wsshWebProfileSerializer.loadProfile = function(profileName)
{
    try
    {
        if (this.logger.enabled) this.logger.debug("loadProfile: " + profileName);

        return this.load(this.getProfile(profileName));
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("loadProfile:", ex);
    }
    return new Array();
}

wsshWebProfileSerializer.saveProfile = function(profileName, items)
{
    try
    {
        if (this.logger.enabled) this.logger.debug("saveProfile: " + profileName);

        this.save(items, this.getProfile(profileName));
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("saveProfile:", ex);
    }
}

wsshWebProfileSerializer.loadUserProfile = function()
{
    try
    {
        this.logger.debug("loadUserProfile");

        return this.load(this.getUserProfile());
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("loadUserProfile:", ex);
    }
    return new Array();
}

wsshWebProfileSerializer.saveUserProfile = function(items)
{
    try
    {
        this.logger.debug("saveUserProfile");

        this.save(items, this.getUserProfile());
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("saveUserProfile:", ex);
    }
}

wsshWebProfileSerializer.loadPredefinedProfile = function()
{
    try
    {
        this.logger.debug("loadPredefinedProfile");

        return this.load(this.getPredefinedProfile());
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("loadPredefinedProfile:", ex);
    }
    return new Array();
}

wsshWebProfileSerializer.savePredefinedProfile = function(items)
{
    try
    {
        this.logger.debug("savePredefinedProfile");

        this.save(items, this.getPredefinedProfile());
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("savePredefinedProfile:", ex);
    }
}
